export default class Preload extends PIXI.Container {
    constructor() {
        super();

        this.preloadAni = null;
        this.theme = null;
        this.themeOk = false;
        this.resOk = false;

        let loader = Application.app.loader;
        loader.baseUrl = "assets/";
        loader.add([
            "img/loading_01.png",
            "img/loading_02.png",
            "img/loading_03.png",
            "img/loading_04.png"
        ]).load(()=>{this.showLoadAni()});
    }

    showLoadAni() {
        var frames = [];
        for (var i = 1; i <= 4; i++) {
            frames.push(PIXI.Texture.from('img/loading_0' + i + ".png"));
        }
        this.preloadAni = new PIXI.AnimatedSprite(frames);
        this.preloadAni.x = Application.width / 2;
        this.preloadAni.y = Application.height / 2;
        this.preloadAni.anchor.set(0.5);
        this.preloadAni.animationSpeed = 0.5;
        this.preloadAni.play();
        this.addChild(this.preloadAni);

        let loader = Application.app.loader;
        let needReadPackRes = true;
        loader.add([
            "skin/HelloworldPanel.json",
            "sheet/test.json",
            "sheet/common.json"
        ]).pre(function(resource, next) {
            if (needReadPackRes) {
                let {url} = resource;
                if (resource.extension == "json") {
                    if (window.wx) {
                        let fileManager = wx.getFileSystemManager();
                        let exsit = fileManager.accessSync(url);
                        if (!exsit) {
                            let content = fileManager.readFileSync(url, "utf8")
                            let json = JSON.parse(content);
                            resource._flags = 2;
                            resource.type = PIXI.LoaderResource.TYPE.JSON;
                            resource.data = json;
                            next();
                        }
                    }
                } else {
                    next();
                }
            } else {
                next();
            }
        }).
        load(()=>{
            this.loadResComplete()
        });

        this.loadTheme();
    }

    loadTheme() {
        this.loadThemeComplete();
        return;

        this.theme = new GOWN.ThemeParser(PIXI.loader.baseUrl + `themes/aeon_desktop.json`);
        this.theme.once(GOWN.Theme.COMPLETE, this.loadThemeComplete, this);
        GOWN.loader.load();
    }

    loadThemeComplete() {
        // 此处可以修改一些样式
        // this.theme.textStyle._fontSize = 24;
        this.themeOk = true;
        this.check();
    }

    loadResComplete() {
        this.resOk = true;
        this.check();
    }

    check() {
        if (this.themeOk && this.resOk) {
            this.preloadAni.destroy();
            this.preloadAni = null;
            this.theme = null;
            this.emit('complete');
        }
    }
}